const proAjax = {
      get: url => {
        return new Promise( (resolve,reject) => {
          var xhr = new XMLHttpRequest()
          xhr.open('GET', url)
          xhr.onreadystatechange = () => {
            if (xhr.readyState == 4) {
              if (xhr.status == 200 || xhr.status == 304) {
                 resolve(xhr.responseText)
              }
            }
          }
          xhr.send()
        }) 
      }
    }
// 封装ajax
var Ajax = {
  get: function(url,fn){
      // XMLHttpRequest对象用于在后台与服务器交换数据
      var xhr=new XMLHttpRequest();
      xhr.open('GET',url,false);
      xhr.onreadystatechange=function(){
          // readyState == 4说明请求已完成
          if(xhr.readyState==4){
              if(xhr.status==200 || xhr.status==304){
                  // console.log(xhr.responseText);
                  fn(xhr.responseText);
              }
          }
      }
      xhr.send();
  },
  post: function(url,data,fn){
      var xhr = new XMLHttpRequest();//第一步：创建需要的对象
      xhr.open('POST', url, true); //第二步：打开连接/***发送json格式文件必须设置请求头 ；如下 - */
      xhr.setRequestHeader("Content-type","application/json");//设置请求头 注：post方式必须设置请求头（在建立连接后设置请求头）var obj = { name: 'zhansgan', age: 18 };
      xhr.send(JSON.stringify(data));//发送请求 将json写入send中
      xhr.onreadystatechange = function () {//请求后的回调接口，可将请求成功后要执行的程序写在其中
          if (xhr.readyState == 4 && xhr.status == 200) {//验证请求是否发送成功
            fn(xhr.responseText)
          }
      }
  }
}

function getCss(ele,css){
  return window.getComputedStyle(ele,null)[css];
}
function do_downright (ball,old_top,old_left) {
  ball.style.top = old_top + 20 +'px'
  ball.style.left = old_left + 20 +'px'
}
function do_downleft (ball,old_top,old_left) {
  ball.style.top = old_top + 20 +'px'
  ball.style.left = old_left - 20 +'px'
}
function do_topright (ball,old_top,old_left) {
  ball.style.top = old_top - 20 +'px'
  ball.style.left = old_left + 20 +'px'
}
function do_topleft (ball,old_top,old_left) {
  ball.style.top = old_top - 20 +'px'
  ball.style.left = old_left - 20 +'px'
}



const ball = document.querySelector('#ball')
const yellow = document.querySelector('#yellow')
const startBtn = document.querySelector('#startBtn')
const end_x = 720
const end_y = 520
var touch_w = parseInt(getCss(yellow,'width')) + parseInt(getCss(ball,'width'))
var touch_h = parseInt(getCss(yellow, 'height')) + parseInt(getCss(ball, 'height'))

// 开始界面 和 结束页面
const startface = document.querySelector('#startface')
const endface = document.querySelector('#endface')
const method = document.querySelector('#method')
const list = document.querySelector('#list')
const author = document.querySelector('#author')

var yellow_w = parseInt(getCss(yellow,'width'))

var timer=null;
const [downright,downleft,topleft,topright] = [1,2,3,4]
// x--left y--top
var direction = downright // 运动方向
var score = document.querySelector('.score') // 玩家得分
var end_score = 0  // 最终得分
var speed = 100 // 球移动速度
var submit = false

function startGame() {
  ball.style.top = 0
  ball.style.left = 0
  direction = downright // 运动方向
  end_score = 0
  speed = 100
  submit = false
  timer=window.setInterval(move,speed)
  startface.style.background = 'none'
  startface.style.display = 'none'
}


function move () {
  var old_top = parseInt(getCss(ball,'top'))
  var old_left = parseInt(getCss(ball,'left'))

  var yellow_top = parseInt(getCss(yellow,'top')) 
  var yellow_bottom = yellow_top + 20
  var yellow_left = parseInt(getCss(yellow,'left'))
  var yellow_right = yellow_left + 100

  var e_ball = document.querySelector('#ball')
  var ball_top = e_ball.offsetTop
  var ball_left = e_ball.offsetLeft
  var ball_right = ball_left + 80

  touch_w = parseInt(getCss(yellow,'width')) + parseInt(getCss(ball,'width'))
  if (direction === downright) {
    // bottom: end_y - 60
    do_downright(e_ball,old_top,old_left)
    if (e_ball.offsetTop === end_y && e_ball.offsetLeft < end_x) {
      document.querySelector('#endscore').innerHTML = end_score
      endface.style.display = 'flex'
      alert('游戏结束了哦')
      window.clearInterval(timer)
    }
    // 碰到底部反方向
    if (e_ball.offsetLeft === end_x) {
      direction = downleft
      do_downleft(e_ball,old_top,old_left)
    }
    // 碰到方块
    if ((yellow_bottom - ball_top  === touch_h) && (Math.max(ball_right,yellow_right) - Math.min(ball_left,yellow_left) - 10 < touch_w)) {
      end_score += 100
      score.innerHTML = end_score
      direction = topright
      do_topright(e_ball,old_top,old_left)
      if (end_score%300 === 0) {
        window.clearInterval(timer)
        if (yellow_w === 20) { yellow_w = 20 } else { yellow_w -= 15 }
        yellow.style.width = yellow_w + 'px'
        if (speed === 20) { speed = 20 } else { speed -= 20 }
        timer=window.setInterval(move,speed)
      }
    }
  }
  if (direction === topright) {
    do_topright(e_ball,old_top,old_left)
    if (e_ball.offsetTop < end_y && e_ball.offsetLeft === end_x) {
      direction = topleft
      do_topleft(e_ball,old_top,old_left)
    }
    if (e_ball.offsetTop === 0) {
      direction = downright
      do_downright(e_ball,old_top,old_left)
    } 
  }
  if (direction === topleft) {
    do_topleft(e_ball,old_top,old_left)
    if (e_ball.offsetTop === 0 && e_ball.offsetLeft < end_x) {
      direction = downleft
      do_downleft(e_ball,old_top,old_left)
    }
    if (e_ball.offsetLeft === 0) {
      direction = topright
      do_topright(e_ball,old_top,old_left)
    }
  }
  if (direction === downleft) {
    do_downleft(e_ball,old_top,old_left)
    if (e_ball.offsetTop < end_y && e_ball.offsetLeft === 0) {
      direction = downright
      do_downright(e_ball,old_top,old_left)
    }
    if (e_ball.offsetTop === end_y) {
      document.querySelector('#endscore').innerHTML = end_score
      endface.style.display = 'flex'
      alert('游戏结束了哦')
      window.clearInterval(timer)
    }
    if ((yellow_bottom - e_ball.offsetTop  === touch_h) && (Math.max(ball_right,yellow_right) - Math.min(ball_left,yellow_left) - 10 < touch_w)) {
      end_score += 100
      score.innerHTML = end_score
      direction = topleft
      do_topleft(e_ball,old_top,old_left)
      if (end_score%300 === 0) {
        window.clearInterval(timer)
        if (yellow_w === 20) { yellow_w = 20 } else { yellow_w -= 15 }
        yellow.style.width = yellow_w + 'px'
        if (speed === 20) { speed = 20 } else { speed -= 20 }
        timer=window.setInterval(move,speed)
      }
    }
  }
}
document.onkeydown=move_yellow;
function move_yellow(event){
  var old=parseInt(getCss(yellow,"left"));
  var space = 800 - parseInt(getCss(yellow,"width"))
  switch(event.keyCode){
    case 37:
    yellow.style.left=(old-20<0)?"0px":(old-20+"px");
    break;
  case 39:
    yellow.style.left=(old+20>space)?`${space}px`:(old+20+"px");
    break;
  default:break;
  }
}

function goback () {
  startface.style.display = 'block'
  endface.style.display = 'none'
  method.style.display = 'none'
  list.style.display = 'none'
  author.style.display = 'none'
}
function getmethod () {
  startface.style.display = 'none'
  method.style.display = 'flex'
}
function getlist () {
  startface.style.display = 'none'
  list.style.display = 'flex'
  var items = document.querySelectorAll('#item')
  Ajax.get('http://localhost:1234/list',function fn(res) {
    var data = JSON.parse(res)
    data.forEach((list, i) => {
      items[i].innerHTML = list.name + '/' +list.score
    });
  })
}

function getauthor () {
  startface.style.display = 'none'
  author.style.display = 'flex'
}

function submitscore () {
  var name = document.querySelector('#name')
  if (!submit) {
    if (name.value === '') {
      alert('请输入名字')
    } else {
      Ajax.post('http://localhost:1234/ball',{ name: name.value, score: end_score },function fn(res) {
        console.log(res);
      })
      alert('提交完成')
      name.value = ' '
      submit = true
    }
  } else {
    alert('你已经提交过了')
  }
}